<?php

namespace app\middleware;

use app\Request;

class Validate
{
    public function handle(Request $request, \Closure $next)
    {
        $path = $request->pathinfo();
        $className = $this->getValidateClassName($path, $action);
        if (class_exists($className)) {
            /**
             * @var $valid \think\Validate
             */
            $valid = new $className();
            if ($valid->hasScene($action) && !$valid->scene($action)->check(input())) {
                $error = $valid->getError();
                return response($error,200, [], 'json');
            }
        }
        return $next($request);
    }

    public function getValidateClassName($path, &$action)
    {
        $namePath = explode( '/', $path);
        $action = $namePath[count($namePath) - 1];
        $className = 'app\\validate';
        foreach ($namePath as $key => $path) {
            if ($key+1==count($namePath)) {
                break;
            }elseif ($key+2 == count($namePath)){
                $className.='\\'.ucfirst($path);
            }else {
                $className.='\\'.$path;
            }
        }
        return $className . 'Validate';
    }
}